package com.itboye.ihomebank.me;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.AvatarDataBeans;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.RoundImageView;
import com.itboye.ihomebank.home.ActivityRealName;
import com.itboye.ihomebank.home.TianXieHeTongActivityFangDong;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CameraPopupWindow;
import com.itboye.ihomebank.util.FuKuanFangShiPopupWindow;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.UploadImage;
import com.itboye.ihomebank.util.UploadImage.OnUploadlistener;
import com.itboye.ihomebank.util.XImageLoader;

/**
 * 个人信息
 * 
 */
public class ActivityMyData extends BaseOtherActivity implements
		OnClickListener, OnUploadlistener, Observer {
	private ImageView close_icon;// 返回图片
	private TextView add_shap_title_tv;// 标题
	private RelativeLayout user_image_layout;// 头像布局
	private RelativeLayout user_name_layout;// 昵称布局
	private RelativeLayout user_sex_layout;// 性别布局
	private RelativeLayout user_phone_layout;// 绑定手机布局
	private RelativeLayout user_move_layout;// 房源管理布局
	private RelativeLayout user_identity_layout;// 身份验证布局
	private RoundImageView usericon_im;// 头像
	private TextView usericon_nicheng;// 昵称
	private TextView usericon_sex;// 性别
	private TextView usericon_phone;// 绑定手机
	private TextView usericon_move;// 房源管理
	private TextView usericon_identity;// 身份验证

	private String phonenumber;// 保存的手机号码

	CameraPopupWindow mCameraPopupWindow;

	public static String AVARTACTION = "com.zhujia.avart";

	private String localSelectPath;
	String sex;
	UserPresenter userPresenter;
	protected String uid;
	private OnClickListener sexClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.open_camera:
				sex = "2";
				break;
			case R.id.pick_image:
				sex = "1";
				break;
			case R.id.camera_cancel_tv:
				sex = "0";
				break;
			default:
				break;
			}
			uid = SPUtils
					.get(ActivityMyData.this, null, SPContants.USER_ID, "")
					+ "";
			userPresenter.updateSex(uid, sex);
		}
	};

	/**
	 * 显示数据
	 */
	private void read() {
		// 昵称
		usericon_nicheng.setText((String) SPUtils.get(ActivityMyData.this,
				null, SPContants.NICK, ""));
		// 电话
		phonenumber = (String) SPUtils.get(ActivityMyData.this, null,
				SPContants.MOBILE, "");
		if (!phonenumber.equals("")) {
			try {
				String hintphone = phonenumber.substring(0, 3) + "****"
						+ phonenumber.substring(7, 11);
				usericon_phone.setText(hintphone);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if ((SPUtils.get(this, null, SPContants.IdentityValidate, "") + "")
				.equals("1")) {
			usericon_identity.setText("已认证");
		} else if ((SPUtils.get(this, null, SPContants.IdentityValidate, "") + "")
				.equals("2")) {
			usericon_identity.setText("待审核");
		} else {
			usericon_identity.setText("未认证");
		}

		initavatar();

		// 性别
		String sex = (String) SPUtils.get(ActivityMyData.this, null,
				SPContants.SEX, "");
		if (!sex.equals("")) {
			try {
				if (sex.equals("0")) {
					usericon_sex.setText("未知");
				} else if (sex.equals("1")) {
					usericon_sex.setText("女");
				} else {
					usericon_sex.setText("男");
				}
			} catch (Exception e) {
			}
		}

	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.close_icon:// 返回
			finish();
			break;
		case R.id.user_image_layout:// 头像布局
			mCameraPopupWindow = new CameraPopupWindow(ActivityMyData.this,
					onclicklister);
			mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.user_name_layout:// 昵称布局
			intent = new Intent(ActivityMyData.this, ActivityNiCheng.class);
			startActivityForResult(intent, 1);
			break;
		case R.id.user_sex_layout:// 性别布局
			mCameraPopupWindow = new CameraPopupWindow(this, sexClickListener);
			mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			((TextView) mCameraPopupWindow.getContentView().findViewById(
					R.id.open_camera)).setText("男");
			((TextView) mCameraPopupWindow.getContentView().findViewById(
					R.id.pick_image)).setText("女");
			((TextView) mCameraPopupWindow.getContentView().findViewById(
					R.id.camera_cancel_tv)).setText("保密");

			// intent = new Intent(ActivityMyData.this, ActivitySex.class);
			// startActivityForResult(intent, 2);
			break;
		case R.id.user_phone_layout:// 绑定手机布局

			// intent = new Intent(ActivityMyData.this,
			// ActivityBindPhone.class);
			// startActivityForResult(intent, 2);
			break;
		case R.id.user_identity_layout:// 身份验证布局
			if ((SPUtils.get(this, null, SPContants.IdentityValidate, "") + "")
					.equals("0")
					|| (SPUtils
							.get(this, null, SPContants.IdentityValidate, "") + "")
							.equals("")) {
				intent = new Intent(ActivityMyData.this, ActivityRealName.class);
				startActivity(intent);
			} else if ((SPUtils
					.get(this, null, SPContants.IdentityValidate, "") + "")
					.equals("2")) {
				ByAlert.alert("实名审核中");
			} else {

			}
			break;

		default:
			break;
		}

	}

	private String picture_name;

	private String fileName;
	/** 使用相机拍照 */
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
	/** 相册剪切 */
	public static final int IMAGE_COMPLETE = 6;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 1) {
				usericon_nicheng.setText("" + data.getStringExtra("nickname"));
			} else if (requestCode == 2) {
				String sexx = data.getStringExtra("sex");
				if (sexx.equals("0")) {
					usericon_sex.setText("未知");
				} else if (sexx.equals("1")) {
					usericon_sex.setText("女");
				} else {
					usericon_sex.setText("男");
				}
			} else if (requestCode == 0) {
				/**
				 * 当选择的图片不为空的话，在获取到图片的途径
				 */
				Uri selectedImage = data.getData();
				localSelectPath = null;
				localSelectPath = getRealPathFromURI(selectedImage);
				String[] img = { localSelectPath };
				UploadImage.getInstance().execute(img, "avatar", this, null);
				mCameraPopupWindow.dismiss();
			} else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
					&& resultCode == RESULT_OK) {
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Log.i("TestFile",
							"SD card is not avaiable/writeable right now.");
					return;
				}
				picture_name = android.text.format.DateFormat.format(
						"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
						+ ".jpg";
				Bundle bundle = data.getExtras();
				Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
				// SavePicInLocal(bitmap);
				FileOutputStream b = null;
				File file = new File("/sdcard/Image/");
				file.mkdirs();// 创建文件夹
				fileName = "/sdcard/Image/" + picture_name;

				try {
					b = new FileOutputStream(fileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				String[] img = { fileName };
				UploadImage.getInstance().execute(img, "avatar", this, null);

				mCameraPopupWindow.dismiss();

			}
		}
	}

	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.open_camera:
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
				} else {
					Toast.makeText(ActivityMyData.this, "请确认已经插入SD卡", 2000)
							.show();
				}
				break;
			case R.id.pick_image:
				Intent intent2 = new Intent();
				intent2.setType("image/*");// 可选择图片视频
				// 修改为以下两句代码
				intent2.setAction(Intent.ACTION_PICK);
				intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
				startActivityForResult(intent2, 0);
				break;
			case R.id.img:
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 该方法用于获取文件的真实路径从URI 从相机拍摄
	 */
	private String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	/**
	 * 头像
	 */
	private void initavatar() {

		String url = "" + SPUtils.get(this, null, SPContants.AVATAR_URL, "");
		System.out.println(url);
		if (!url.equals("")) {
			if (url.startsWith("http:")) {
				XImageLoader.load(url, usericon_im);
			} else if (url.equals("0")) {
				usericon_im.setImageResource(R.drawable.default_head);
			} else {
				XImageLoader.load(NetPublicConstant.IMAGE_URL + url,
						usericon_im);
			}
		} else {
			usericon_im.setImageResource(R.drawable.default_head);
		}

	}

	/**
	 * 上传成功
	 */
	@Override
	public void OnSuccess(ArrayList<AvatarDataBeans> resultData) {
		ByAlert.alert("上传成功");
		SPUtils.put(this, "", SPContants.AVATAR_URL, resultData.get(0)
				.getImgurl());
		initavatar();
		Intent intent = new Intent(AVARTACTION);
		sendBroadcast(intent);

	}

	/**
	 * 上传失败
	 */
	@Override
	public void OnError(String resultData) {
		ByAlert.alert(resultData);

	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_gerendata;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		add_shap_title_tv.setText("个人信息");
		userPresenter = new UserPresenter(this);
		read();
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == UserPresenter.updateSex_success) {
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == UserPresenter.updateSex_fail) {
				ByAlert.alert(entity.getData());
			}
		}
	}

}
